package cn.xiaoyu.su.controller;

import cn.xiaoyu.su.constant.CacheKey;
import cn.xiaoyu.su.constant.TimeConstant;
import cn.xiaoyu.su.enums.BizCodeEnum;
import cn.xiaoyu.su.enums.SendCodeEnum;
import cn.xiaoyu.su.controller.request.SendCodeRequest;
import cn.xiaoyu.su.service.NotifyService;
import cn.xiaoyu.su.util.CommonUtil;
import cn.xiaoyu.su.util.JsonData;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author sufs
 * @date 2022/10/27 14:54
 */
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Producer captchaProducer;

    /**
     * 图形验证码
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaKey = getCaptchaKey(request);

        String captchaText = captchaProducer.createText();

        redisTemplate.opsForValue().set(captchaKey,captchaText, TimeConstant.CAPTCHA_EXPIRED_TIME, TimeUnit.MILLISECONDS);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        try(ServletOutputStream outputStream = response.getOutputStream()) {

            ImageIO.write(bufferedImage, "jpg", outputStream);

            outputStream.flush();

        } catch (IOException e) {
            log.error("生成验证码图片异常：{}",e);
        }

    }

    /**
     * 发送短信验证码
     * @param sendCodeRequest
     * @param request
     * @return
     */
    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {

        String captchaKey = getCaptchaKey(request);

        String cacheCaptcha = redisTemplate.opsForValue().get(captchaKey);

        if (StringUtils.isNotBlank(cacheCaptcha) && StringUtils.isNotBlank(sendCodeRequest.getCode()) && cacheCaptcha.equalsIgnoreCase(sendCodeRequest.getCode())) {
            //验证码核对上之后，记得从缓存删除key
            redisTemplate.delete(captchaKey);

            return notifyService.sendCode(SendCodeEnum.REGISTER,sendCodeRequest.getTelePhone());

        } else {
            //验证码核对不上
            log.error("验证码不正确：{}",sendCodeRequest);
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

    }

    private String getCaptchaKey(HttpServletRequest request) {
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");

        String captchaKey = String.format(CacheKey.CAPTCHA_KEY, CommonUtil.MD5(ipAddr + userAgent));
        return captchaKey;
    }
}
